'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'

export default function Navbar() {
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [isLoggingOut, setIsLoggingOut] = useState(false)
  const router = useRouter()

  // 检查登录状态的函数
  const checkLoginStatus = () => {
    console.log(document.cookie)
    const token = document.cookie.includes('token=')
    setIsLoggedIn(token)
    console.log('token:', token)
  }

  useEffect(() => {
    checkLoginStatus()
    
    // 监听自定义事件
    const handleAuthChange = () => {
      checkLoginStatus()
    }
    window.addEventListener('auth-change', handleAuthChange)
    window.addEventListener('popstate', handleAuthChange)

    return () => {
      window.removeEventListener('auth-change', handleAuthChange)
      window.removeEventListener('popstate', handleAuthChange)
    }
  }, [])

  const handleLogout = async () => {
    try {
      setIsLoggingOut(true)
      const res = await fetch('/api/auth/logout', {
        method: 'POST'
      })
      
      if (res.ok) {
        setIsLoggedIn(false)
        window.location.href = '/'
      }
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      setIsLoggingOut(false)
    }
  }

  return (
    <nav className="w-full border-b border-gray-200 bg-[#1e3a8a]">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16">
          <div className="flex items-center">
            <Link href="/" className="text-lg font-semibold text-white">
              Next Admin
            </Link>
          </div>
          <div className="flex items-center space-x-4">
            <Link href="/docs" className="text-white/80 hover:text-white transition-colors">
              API文档
            </Link>
            {isLoggedIn && (
              <>
                <Link href="/users" className="text-white/80 hover:text-white transition-colors">
                  用户管理
                </Link>
                <Link href="/regions" className="text-white/80 hover:text-white transition-colors">
                  区划管理
                </Link>
              </>
            )}
            {isLoggedIn ? (
              <button
                onClick={handleLogout}
                disabled={isLoggingOut}
                className="text-white/80 hover:text-white transition-colors disabled:opacity-50"
              >
                {isLoggingOut ? '退出中...' : '退出'}
              </button>
            ) : (
              <Link
                href="/login"
                className="text-white/80 hover:text-white transition-colors"
              >
                登录
              </Link>
            )}
          </div>
        </div>
      </div>
    </nav>
  )
} 